// 导入 express 模块
const express = require("express");
const userModel = require("../../models/userModel");
const md5 = require("md5");

// 路由
var router = express.Router();

router.get("/reg", (req, res) => {
  res.render("auth/reg");
  // res.send("注册页面");
});

router.post("/reg", (req, res) => {
  console.log(req.body);
  userModel.create(
    {
      ...req.body,
      password: md5(req.body.password),
    },
    (err, data) => {
      if (err) {
        res.send(err);
        return;
      }
      // res.send("注册成功");
      res.render("success", {
        msg: "注册成功",
        url: "/auth/login",
      });
    },
  );
});

router.get("/login", (req, res) => {
  res.render("auth/login");
});

router.post("/login", (req, res) => {
  // 获取用户名和密码
  let { username, password } = req.body;
  console.log(username, password);
  // 查询数据库
  userModel.findOne(
    {
      username: username,
      password: md5(password),
    },
    (err, data) => {
      if (err) {
        // console.log("查询数据库失败");
        res.render("error", {
          message: "登录失败",
          error: {
            status: err.status,
            stack: err.stack,
          },
        });
        return;
      }
      console.log(data);
      if (data == null) {
        res.render("success", {
          msg: "账号或密码错误",
          url: "/auth/reg",
        });
      } else {
        req.session.username = data.username;
        req.session._id = data._id;
        res.render("success", {
          msg: "登录成功",
          url: "/account",
        });
      }
    },
  );
});

// router.get("/logout", (req, res) => {
router.post("/logout", (req, res) => {
  req.session.destroy(() => {
    res.render("success", {
      msg: "退出成功",
      url: "/auth/login",
    });
  });
});

module.exports = router;
